import { computed, nextTick, ref } from 'vue'
import { createGoodsSkusCard, updateGoodsSkusCard, deleteGoodsSkusCard, sortGoodsSkusCard, createGoodsSkusCardValue, updateGoodsSkusCardValue, deleteGoodsSkusCardValue, chooseAndSetGoodsSkusCard } from '@/api/goods'
import { useArrayMoveUp, useArrayMoveDown, cartesianProductOf } from "@/composables/util"

// 当前商品ID
export const goodsId = ref(0)
// 规格选项列表
export const sku_card_list = ref([])
// 按钮加载
export const btnLoading = ref(false)
// 排序加载
export const bodyLoading = ref(false)
// 规格表格
export const skus_list = ref([])

// 初始化规格选项列表
export const initSkuCardList = res => {
  sku_card_list.value = res.goodsSkusCard.map(item => {
    item.text = item.name
    item.loading = false
    item.goodsSkusCardValue.map(v => {
      v.text = v.value || "属性值"
      return v
    })
    return item
  })
  skus_list.value = res.goodsSkus
}

// 初始化规格值
export const initSkuCardItem = id => {
  const item = sku_card_list.value.find(v => v.id === id)
  const inputValue = ref('')
  const inputVisible = ref(false)
  const InputRef = ref(null)
  const loading = ref(false)

  const handleClose = async tag => {
    try {
      loading.value = true
      await deleteGoodsSkusCardValue(tag.id)
      let i = item.goodsSkusCardValue.findIndex(v => v.id === tag.id)
      if (i !== -1) {
        item.goodsSkusCardValue.splice(i, 1)
      }
      getTableData()
    } finally {
      loading.value = false
    }
  }

  const showInput = () => {
    inputVisible.value = true
    nextTick(() => {
      InputRef.value.input.focus()
    })
  }

  const handleInputConfirm = async () => {
    if (!inputValue.value) {
      inputVisible.value = false
      return
    }
    try {
      loading.value = true
      const res = await createGoodsSkusCardValue({
        goods_skus_card_id: id,
        name: item.name,
        order: 50,
        value: inputValue.value
      })
      inputValue.value = ''
      inputVisible.value = false
      loading.value = false
      item.goodsSkusCardValue.push({ ...res, text: res.value })
      getTableData()
    } catch {
      inputValue.value = ''
      inputVisible.value = false
      loading.value = false
    }
  }
  const handleChange = async (value, tag) => {
    try {
      loading.value = true
      await updateGoodsSkusCardValue(tag.id, {
        goods_skus_card_id: id,
        name: item.name,
        order: tag.order,
        value: value
      })
      tag.value = value
      getTableData()
      loading.value = false
    } catch {
      tag.text = tag.value
      loading.value = false
    }
  }
  return {
    item,
    inputValue,
    inputVisible,
    InputRef,
    loading,
    handleClose,
    showInput,
    handleInputConfirm,
    handleChange
  }
}

// 初始化表格
export const initSkuTable = () => {
  const skuLables = computed(() => sku_card_list.value.filter(v => v.goodsSkusCardValue.length > 0))
  const tableHeader = computed(() => {
    let length = skuLables.value.length
    return [
      {
        name: '商品规格',
        colspan: length,
        width: '',
        rowspan: length > 0 ? 1 : 2
      },
      {
        name: '销售价',
        width: '50',
        rowspan: 2
      },
      {
        name: '市场价',
        width: '50',
        rowspan: 2
      },
      {
        name: '成本价',
        width: '50',
        rowspan: 2
      },
      {
        name: '库存',
        width: '50',
        rowspan: 2
      },
      {
        name: '体积',
        width: '50',
        rowspan: 2
      },
      {
        name: '重量',
        width: '50',
        rowspan: 2
      },
      {
        name: '编码',
        width: '50',
        rowspan: 2
      },
    ]
  })
  return {
    skuLables,
    tableHeader,
    skus_list
  }
}

// 添加规格选项
export const addSkuCardEvent = async () => {
  try {
    btnLoading.value = true
    const res = await createGoodsSkusCard({
      goods_id: goodsId.value,
      name: "规格选项",
      order: 50,
      type: 0
    })
    getTableData()
    sku_card_list.value.push({
      ...res,
      text: res.name,
      loading: false,
      goodsSkusCardValue: []
    })
  } finally {
    btnLoading.value = false
  }
}

// 修改规格选项
export const handleUpdate = async item => {
  try {
    item.loading = true
    await updateGoodsSkusCard(item.id, {
      goods_id: item.goods_id,
      name: item.text,
      order: item.order,
      type: 0
    })
    item.loading = false
    getTableData()
  } catch {
    item.loading = false
    item.text = item.name
  }
}

// 删除规格选项
export const handleDelete = async item => {
  try {
    item.loading = true
    await deleteGoodsSkusCard(item.id)
    const index = sku_card_list.value.findIndex(v => v.id === item.id)
    if (index !== -1) {
      sku_card_list.value.splice(index, 1)
    }
    getTableData()
  } catch {
    if (item.loading) item.loading = false
  }
}

// 排序规格选项
export const sortCard = async (action, index) => {
  let oList = JSON.parse(JSON.stringify(sku_card_list.value))
  let func = action === "up" ? useArrayMoveUp : useArrayMoveDown
  func(oList, index)
  let sortData = oList.map((o, i) => {
    return {
      id: o.id,
      order: i + 1
    }
  })
  try {
    bodyLoading.value = true
    await sortGoodsSkusCard({ sortdata: sortData })
    func(sku_card_list.value, index)
    getTableData()
  } finally {
    bodyLoading.value = false
  }
}

// 选择设置规格
export const handleChooesSetGoodsSkusCard = async (id, data) => {
  try {
    let item = sku_card_list.value.find(v => v.id === id)
    item.loading = true
    const res = await chooseAndSetGoodsSkusCard(id, data)
    item.name = item.text = res.goods_skus_card.name
    item.goodsSkusCardValue = res.goods_skus_card_value.map(v => {
      v.text = v.value || '属性值'
      return v
    })
    getTableData()
  } finally {
    item.loading = false
  }
}

// 获取规格数据
const getTableData = () => {
  setTimeout(() => {
    if (sku_card_list.value.length === 0) return []

    let list = []
    sku_card_list.value.forEach(o => {
      if (o.goodsSkusCardValue && o.goodsSkusCardValue.length > 0) {
        list.push(o.goodsSkusCardValue)
      }
    })

    if (list.length == 0) {
      return []
    }

    let arr = cartesianProductOf(...list)

    // 获取之前的规格列表，将规格ID排序之后转化成字符串
    let beforeSkuList = JSON.parse(JSON.stringify(skus_list.value)).map(o => {
      if (!Array.isArray(o.skus)) {
        o.skus = Object.keys(o.skus).map(k => o.skus[k])
      }
      o.skusId = o.skus.sort((a, b) => a.id - b.id).map(s => s.id).join(",")
      return o
    })

    skus_list.value = []
    skus_list.value = arr.map(skus => {
      let o = getBeforeSkuItem(JSON.parse(JSON.stringify(skus)), beforeSkuList)
      return {
        code: o?.code || "",
        cprice: o?.cprice || "0.00",
        goods_id: goodsId.value,
        image: o?.image || "",
        oprice: o?.oprice || "0.00",
        pprice: o?.pprice || "0.00",
        skus,
        stock: o?.stock || 0,
        volume: o?.volume || 0,
        weight: o?.weight || 0,
      }
    })
  }, 100)
}

const getBeforeSkuItem = (skus, beforeSkuList) => {
  let skusId = skus.sort((a, b) => a.id - b.id).map(s => s.id).join(",")
  return beforeSkuList.find(o => {
    if (skus.length > o.skus.length) {
      return skusId.indexOf(o.skusId) != -1
    }
    return o.skusId.indexOf(skusId) != -1
  })
}